package de.bensoft.jrail.business.service;

import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.Query;

import de.bensoft.jrail.business.entity.Trackplan;
import de.bensoft.jrail.business.entity.TrackplanSegment;

public class TrackplanService {
	
	public static final Long STANDARD_SIZE = 60l;
	
	@Inject
	EntityManager em;
	
	public Trackplan getTrackplanByIdentifier(String identifier) {
		Query q = em.createNamedQuery(Trackplan.FIND_BY_IDENTIFIER);
		q.setParameter(Trackplan.BINDING_IDENTIFIER, identifier);
		
		Trackplan t = null;
		
		try {
			t = (Trackplan)q.getSingleResult();
		} catch(NoResultException e) {
			
		}
		
		if(t == null) {
			t = new Trackplan();
			t.setIdentifier(identifier);
			t.setSize(STANDARD_SIZE);
		}
		
		return t;
	}
	
	
	public Trackplan saveTrackplan(Trackplan tp) {
		
		for(TrackplanSegment s : tp.getSegments()) {
			s.setTrackplan(tp);
		}
		
		em.getTransaction().begin();
		
		if(tp.getId() == null)
			em.persist(tp);
		else
			tp = em.merge(tp);
		
		em.getTransaction().commit();
		
		return tp;
	}
	
	public void deleteTrackplanSegment(TrackplanSegment s) {
		em.getTransaction().begin();
		em.remove(s);
		em.getTransaction().commit();
	}
	
	public TrackplanSegment saveTrackplanSegment(TrackplanSegment s) {
		em.getTransaction().begin();
		
		if(s.getId() == null)
			em.persist(s);
		else
			s = em.merge(s);
		
		em.getTransaction().commit();
		
		return s;
	}
}
